/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nxlv2.nomad.view.ficheClient;

import com.nxlv2.nomad.accessdb.services.AdresseServices;
import com.nxlv2.nomad.accessdb.services.ArticleServices;
import com.nxlv2.nomad.accessdb.services.ClientServices;
import com.nxlv2.nomad.accessdb.services.CommandeServices;
import com.nxlv2.nomad.accessdb.services.ContactServices;
import com.nxlv2.nomad.accessdb.services.DemandeServices;
import com.nxlv2.nomad.accessdb.services.DetailCommandeServices;
import com.nxlv2.nomad.accessdb.services.DetailDemandeServices;
import com.nxlv2.nomad.accessdb.services.PrixServices;
import com.nxlv2.nomad.accessdb.services.TvaServices;
import com.nxlv2.nomad.accessdb.services.UtilisateurServices;
import com.nxlv2.nomad.businessobjects.Adresse;
import com.nxlv2.nomad.businessobjects.Article;
import com.nxlv2.nomad.businessobjects.Client;
import com.nxlv2.nomad.businessobjects.Commande;
import com.nxlv2.nomad.businessobjects.Contact;
import com.nxlv2.nomad.businessobjects.Demande;
import com.nxlv2.nomad.businessobjects.DetailCommande;
import com.nxlv2.nomad.businessobjects.DetailDemande;
import com.nxlv2.nomad.businessobjects.EtatCommande;
import com.nxlv2.nomad.businessobjects.Prix;
import com.nxlv2.nomad.businessobjects.Tva;
import com.nxlv2.nomad.view.Welcome;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import static org.apache.http.HttpHeaders.USER_AGENT;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.joda.time.DateTime;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 *
 * @author Casey
 */
public class SynchroAction extends AbstractAction {

    private final Welcome welcomeUI;

    public SynchroAction(Welcome welcomeUI) {
        super();
        this.welcomeUI = welcomeUI;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        try {
            System.out.print("sync");
            String url = "http://127.0.0.1/NewFilRouge/receive";

            HttpClient client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);

            // add header
            post.setHeader("User-Agent", USER_AGENT);

            List<NameValuePair> urlParameters = new ArrayList<>();

            urlParameters.add(new BasicNameValuePair("user", "[" + this.welcomeUI.getUser().toJSONString() + "]"));
            urlParameters.add(new BasicNameValuePair("clients", this.getClientsJSON()));
            urlParameters.add(new BasicNameValuePair("contacts", this.getContactsJSON()));
            urlParameters.add(new BasicNameValuePair("adresses", this.getAdressesJSON()));
            urlParameters.add(new BasicNameValuePair("tva", this.getTvaJSON()));
            urlParameters.add(new BasicNameValuePair("prix", this.getPrixJSON()));
            urlParameters.add(new BasicNameValuePair("demandes", this.getDemandesJSON()));
            urlParameters.add(new BasicNameValuePair("detailDemandes", this.getDetailDemandesJSON()));
            urlParameters.add(new BasicNameValuePair("commandes", this.getCommandesJSON()));
            urlParameters.add(new BasicNameValuePair("detailCommandes", this.getDetailCommandesJSON()));
            urlParameters.add(new BasicNameValuePair("listDetailDemandes", this.getListeIdDetailDemandeJSON()));
            urlParameters.add(new BasicNameValuePair("listeClients", this.getListeIdClientJSON()));
            urlParameters.add(new BasicNameValuePair("listeContacts", this.getListeIdContactJSON()));
            urlParameters.add(new BasicNameValuePair("listeAdresses", this.getListeIdAdresseJSON()));

            post.setEntity(new UrlEncodedFormEntity(urlParameters));

            System.out.println(post);

            HttpResponse response = client.execute(post);
            System.out.println("Response Code : "
                    + response.getStatusLine().getStatusCode());

            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            saveRetour(result);

            // maj dateSynchro user
            UtilisateurServices srvU = new UtilisateurServices();
            this.welcomeUI.getUser().setDateSynchro(new DateTime());
            srvU.update(this.welcomeUI.getUser());
            System.out.println("maj dateSynchro user");
            
            // actualisation de la liste client sur welcome
            this.welcomeUI.setListClient();

        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(SynchroAction.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SynchroAction.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private String getClientsJSON() {

        UtilisateurServices srvU = new UtilisateurServices();
        List<Client> clients = srvU.getClientsMaj(this.welcomeUI.getUser());

        int nbClient = clients.size();
        String clientsJson = "[";

        for (int i = 0; i < nbClient; i++) {
            if (0 != i) {
                clientsJson += ",";
            }
            clientsJson += clients.get(i).toJSONString();
        }
        clientsJson += "]";

        return clientsJson;
    }

    private String getContactsJSON() {

        UtilisateurServices srvU = new UtilisateurServices();
        ClientServices srvCl = new ClientServices();
        List<Client> clients = srvU.getClients(this.welcomeUI.getUser());

        String contactsJson = "[";
        int i = 0;

        for (Client client : clients) {
            List<Contact> contacts = srvCl.getContactsMaj(client);

            for (Contact contact : contacts) {
                if (0 != i) {
                    contactsJson += ",";
                } else {
                    i = 1;
                }
                contactsJson += "{\"client\":\"" + client.getIdAppli() + "\"}," + contact.toJSONString();
            }
        }
        contactsJson += "]";

        return contactsJson;
    }

    private String getAdressesJSON() {

        UtilisateurServices srvU = new UtilisateurServices();
        ClientServices srvCl = new ClientServices();
        List<Client> clients = srvU.getClients(this.welcomeUI.getUser());

        String adressesJson = "[";
        int i = 0;

        for (Client client : clients) {
            List<Adresse> adresses = srvCl.getAdressesMaj(client);

            for (Adresse adresse : adresses) {
                if (0 != i) {
                    adressesJson += ",";
                } else {
                    i = 1;
                }
                adressesJson += "{\"client\":\"" + client.getIdAppli() + "\"}," + adresse.toJSONString();
            }
        }
        adressesJson += "]";

        return adressesJson;
    }

    private String getArticlesJSON() {

        UtilisateurServices srvU = new UtilisateurServices();
        ClientServices srvCl = new ClientServices();
        List<Client> clients = srvU.getClients(this.welcomeUI.getUser());

        String articlesJson = "[";
        int i = 0;
        System.out.println(clients);
        for (Client client : clients) {
            List<Article> articles = srvCl.getArticlesMaj(client);
            System.out.println(articles);
            for (Article article : articles) {
                if (0 != i) {
                    articlesJson += ",";
                } else {
                    i = 1;
                }
                articlesJson += article.toJSONString();
            }
        }
        articlesJson += "]";

        return articlesJson;
    }

    private String getTvaJSON() {

        TvaServices srvTva = new TvaServices();
        List<Tva> tvas = srvTva.getTvaMaj(this.welcomeUI.getUser().getIdAppli());

        String tvaJson = "[";
        int i = 0;

        for (Tva tva : tvas) {

            if (0 != i) {
                tvaJson += ",";
            } else {
                i = 1;
            }
            tvaJson += tva.toJSONString();

        }
        tvaJson += "]";

        return tvaJson;
    }

    private String getPrixJSON() {

        UtilisateurServices srvU = new UtilisateurServices();
        ClientServices srvCl = new ClientServices();
        ArticleServices srvArt = new ArticleServices();
        List<Client> clients = srvU.getClients(this.welcomeUI.getUser());

        String prixJson = "[";
        int i = 0;

        for (Client client : clients) {
            List<Article> articles = srvCl.getArticles(client);

            for (Article article : articles) {
                List<Prix> prixs = srvArt.getPrixMaj(article);

                for (Prix prix : prixs) {
                    if (0 != i) {
                        prixJson += ",";
                    } else {
                        i = 1;
                    }
                    prixJson += "{\"article\":\"" + article.getReference() + "\"}," + prix.toJSONString();
                }

            }
        }
        prixJson += "]";

        return prixJson;
    }

    private String getDemandesJSON() {

        UtilisateurServices srvU = new UtilisateurServices();
        ClientServices srvCl = new ClientServices();
        DemandeServices srvDem = new DemandeServices();
        List<Client> clients = srvU.getClients(this.welcomeUI.getUser());

        String demandeJson = "[";
        int i = 0;

        for (Client client : clients) {
            List<Demande> demandes = srvCl.getDemandesMaj(client);

            for (Demande demande : demandes) {

                if (0 != i) {
                    demandeJson += ",";
                } else {
                    i = 1;
                }
                demandeJson += "{\"client\":\"" + client.getIdAppli() + "\"}," + demande.toJSONString();

            }
        }
        demandeJson += "]";

        return demandeJson;
    }

    private String getDetailDemandesJSON() {

        UtilisateurServices srvU = new UtilisateurServices();
        ClientServices srvCl = new ClientServices();
        DemandeServices srvDem = new DemandeServices();
        DetailDemandeServices srvdd = new DetailDemandeServices();
        List<Client> clients = srvU.getClients(this.welcomeUI.getUser());

        String detailDemandeJson = "[";
        int i = 0;

        for (Client client : clients) {
            List<Demande> demandes = srvCl.getDemandes(client);

            for (Demande demande : demandes) {
                List<DetailDemande> detailDemandes = srvDem.getDetailDemandesMaj(demande);

                for (DetailDemande detailDemande : detailDemandes) {
                    if (0 != i) {
                        detailDemandeJson += ",";
                    } else {
                        i = 1;
                    }

                    detailDemandeJson += "{\"demande\":\"" + demande.getIdAppli()
                            + "\",\"article\":\"" + srvdd.getArticle(detailDemande).getIdBase()
                            + "\",\"prix\":\"" + srvdd.getPrix(detailDemande).getIdAppli() + "\"},"
                            + detailDemande.toJSONString();
                }

            }
        }
        detailDemandeJson += "]";

        return detailDemandeJson;
    }

    private String getCommandesJSON() {

        UtilisateurServices srvU = new UtilisateurServices();
        ClientServices srvCl = new ClientServices();
        CommandeServices srvCom = new CommandeServices();
        List<Client> clients = srvU.getClients(this.welcomeUI.getUser());

        String commandeJson = "[";
        int i = 0;

        for (Client client : clients) {
            List<Commande> commandes = srvCl.getCommandesMaj(client);

            for (Commande commande : commandes) {

                if (0 != i) {
                    commandeJson += ",";
                } else {
                    i = 1;
                }
                commandeJson += "{\"client\":\"" + client.getIdAppli() + "\"}," + commande.toJSONString();

            }
        }
        commandeJson += "]";

        return commandeJson;
    }

    private String getDetailCommandesJSON() {

        UtilisateurServices srvU = new UtilisateurServices();
        ClientServices srvCl = new ClientServices();
        CommandeServices srvCom = new CommandeServices();
        DetailCommandeServices srvdc = new DetailCommandeServices();
        List<Client> clients = srvU.getClients(this.welcomeUI.getUser());

        String commandeJson = "[";
        int i = 0;

        for (Client client : clients) {
            List<Commande> commandes = srvCl.getCommandes(client);

            for (Commande commande : commandes) {
                List<DetailCommande> detailCommandes = srvCom.getDetailCommandesMaj(commande);

                for (DetailCommande detailCommande : detailCommandes) {
                    if (0 != i) {
                        commandeJson += ",";
                    } else {
                        i = 1;
                    }
                    commandeJson += "{\"commande\":\"" + commande.getIdAppli()
                            + "\",\"article\":\"" + srvdc.getArticle(detailCommande).getIdBase()
                            + "\",\"prix\":\"" + srvdc.getPrix(detailCommande).getIdAppli() + "\"},"
                            + detailCommande.toJSONString();
                }

            }
        }
        commandeJson += "]";

        return commandeJson;
    }

    private String getListeIdDetailDemandeJSON() {
        UtilisateurServices srvU = new UtilisateurServices();
        ClientServices srvCl = new ClientServices();
        DemandeServices srvDem = new DemandeServices();
        DetailDemandeServices srvdd = new DetailDemandeServices();
        List<Client> clients = srvU.getClients(this.welcomeUI.getUser());

        String list = "[";
        int i = 0;

        for (Client client : clients) {
            List<Demande> demandes = srvCl.getDemandes(client);

            for (Demande demande : demandes) {
                List<DetailDemande> detailDemandes = srvDem.getDetailDemandes(demande);
                if (0 != i) {
                    list += "\"},";
                }
                i = 0;
                list += "{\"demande\":\"" + demande.getIdAppli()
                        + "\",\"type\":\"" + demande.getTypeDemande().getId()
                        + "\",\"detail\":\"";
                for (DetailDemande detailDemande : detailDemandes) {
                    if (0 != i) {
                        list += ",";
                    } else {
                        i = 1;
                    }
                    list += detailDemande.getIdAppli();
                }
            }
        }
        list += "\"}]";

        return list;
    }
    private String getListeIdClientJSON() {
        UtilisateurServices srvU = new UtilisateurServices();
        List<Client> clients = srvU.getClients(this.welcomeUI.getUser());

        String list = "[{\"listeClient\":\"";
        int i = 0;

        for (Client client : clients) {
 
            if (0 != i) {
                list += ",";
            } else {
                i = 1;
            }
            list += client.getIdAppli();             
            
        }
        list += "\"}]";

        return list;
    }
    private String getListeIdContactJSON() {
        UtilisateurServices srvU = new UtilisateurServices();
        ClientServices srvCl = new ClientServices();        
        List<Client> clients = srvU.getClients(this.welcomeUI.getUser());

        String list = "[";
       
        int j = 0;
        
        for (Client client : clients) {
            List<Contact> contacts = srvCl.getContacts(client);
            if (0 != j) {
                list += ",";
            } else {
                j = 1;
            }
            list += "{\"client\":\""+ client.getIdAppli()
                    + "\",\"listeContact\":\"";
             int i = 0;
            for(Contact contact : contacts){
                if (0 != i) {
                    list += ",";
                } else {
                    i = 1;
                }
                list += contact.getIdAppli();
            }
            list += "\"}";
        }
        list += "]";

        return list;
    }
    private String getListeIdAdresseJSON() {
        UtilisateurServices srvU = new UtilisateurServices();
        ClientServices srvCl = new ClientServices();        
        List<Client> clients = srvU.getClients(this.welcomeUI.getUser());

        String list = "[";
       
        int j = 0;
        
        for (Client client : clients) {
            List<Adresse> adresses = srvCl.getAdresses(client);
            if (0 != j) {
                list += ",";
            } else {
                j = 1;
            }
            list += "{\"client\":\""+ client.getIdAppli()
                    + "\",\"listeAdresse\":\"";
             int i = 0;
            for(Adresse adresse : adresses){
                if (0 != i) {
                    list += ",";
                } else {
                    i = 1;
                }
                list += adresse.getIdAppli();
            }
            list += "\"}";
        }
        list += "]";

        return list;
    }

    private void saveRetour(StringBuffer retour) {

        System.out.println(retour);
        try {

            JSONParser parser = new JSONParser();
            Object obj = parser.parse(retour.toString());
            JSONObject jsonObject = (JSONObject) obj;

//            clients
            if (jsonObject.containsKey("clients")) {
                JSONArray nivone = (JSONArray) jsonObject.get("clients");

                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
                    ClientServices srvcl = new ClientServices();
                    Client cl = srvcl.get(Integer.parseInt(nivtwo.get("idAppli").toString()));
                    cl.setIdBase(Integer.parseInt(nivtwo.get("idBase").toString()));
                    srvcl.update(cl);
                }
            }
//            "contacts"
            if (jsonObject.containsKey("contacts")) {
                JSONArray nivone = (JSONArray) jsonObject.get("contacts");

                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
                    ContactServices srvct = new ContactServices();
                    Contact ct = srvct.get(Integer.parseInt(nivtwo.get("idAppli").toString()));
                    ct.setIdBase(Integer.parseInt(nivtwo.get("idBase").toString()));
                    srvct.update(ct);
                }
            }
//            "adresses"
            if (jsonObject.containsKey("adresses")) {
                JSONArray nivone = (JSONArray) jsonObject.get("adresses");

                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
                    AdresseServices srvad = new AdresseServices();
                    Adresse ad = srvad.get(Integer.parseInt(nivtwo.get("idAppli").toString()));
                    ad.setIdBase(Integer.parseInt(nivtwo.get("idBase").toString()));
                    srvad.update(ad);
                }
            }
//            "tva"
            if (jsonObject.containsKey("tva")) {
                JSONArray nivone = (JSONArray) jsonObject.get("tva");

                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
                    TvaServices srvtva = new TvaServices();
                    Tva tva = srvtva.get(Integer.parseInt(nivtwo.get("idAppli").toString()));
                    tva.setIdBase(Integer.parseInt(nivtwo.get("idBase").toString()));
                    srvtva.update(tva);
                }
            }
//            "prix"
            if (jsonObject.containsKey("prix")) {
                JSONArray nivone = (JSONArray) jsonObject.get("prix");

                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
                    PrixServices srvpr = new PrixServices();
                    Prix pr = srvpr.get(Integer.parseInt(nivtwo.get("idAppli").toString()));
                    pr.setIdBase(Integer.parseInt(nivtwo.get("idBase").toString()));
                    srvpr.update(pr);
                }
            }
//            "demandes"
            if (jsonObject.containsKey("demandes")) {
                JSONArray nivone = (JSONArray) jsonObject.get("demandes");

                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
                    DemandeServices srvdem = new DemandeServices();
                    List<Demande> listDem = srvdem.get(Integer.parseInt(nivtwo.get("idAppli").toString()));
                    for (Demande dem : listDem) {
                        dem.setIdBase(Integer.parseInt(nivtwo.get("idBase").toString()));
                        srvdem.update(dem);
                    }
                }
            }

//            detailDemandes
            if (jsonObject.containsKey("detailDemandes")) {
                JSONArray nivone = (JSONArray) jsonObject.get("detailDemandes");

                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
                    DetailDemandeServices srvdd = new DetailDemandeServices();
                    List<DetailDemande> listDd = srvdd.get(Integer.parseInt(nivtwo.get("idAppli").toString()));
                    // ne y en avoir qu'un c un id de ligne... je sais pas pourquoi List ici... pas grave ;)
                    DetailDemande dd = listDd.get(0);
                    dd.setIdBase(Integer.parseInt(nivtwo.get("idBase").toString()));
                    srvdd.update(dd);
                }
            }

//            commandes
            if (jsonObject.containsKey("commandes")) {
                JSONArray nivone = (JSONArray) jsonObject.get("commandes");

                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
                    CommandeServices srvcom = new CommandeServices();
                    Commande com = srvcom.get(Integer.parseInt(nivtwo.get("idAppli").toString()));
                    com.setIdBase(Integer.parseInt(nivtwo.get("idBase").toString()));
                    srvcom.update(com);
                }
            }
//            detailCommandes
            if (jsonObject.containsKey("detailCommandes")) {
                JSONArray nivone = (JSONArray) jsonObject.get("detailCommandes");

                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
                    DetailCommandeServices srvdc = new DetailCommandeServices();
                    DetailCommande dc = srvdc.get(Integer.parseInt(nivtwo.get("idAppli").toString()));
                    dc.setIdBase(Integer.parseInt(nivtwo.get("idBase").toString()));
                    srvdc.update(dc);
                }
            }
            System.out.println("save retour ok");

            // majClients [{"id_societe":"26","client_societe":"1","id_utilisateur":"18",
            // "delete":"0","id_appli":"1","nom_societe":"Renault"}]
            if (jsonObject.containsKey("majClients")) {
                JSONArray nivone = (JSONArray) jsonObject.get("majClients");
                ClientServices srvcl = new ClientServices();
                String majIdClient = "[";
                int icl = 0;
                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
                    Client cl = new Client(Integer.parseInt(nivtwo.get("id_societe").toString()),
                            Integer.parseInt(nivtwo.get("idAppli").toString()), nivtwo.get("nom_societe").toString());

                    if (cl.getIdAppli() > 0) {
                        // update
                        srvcl.update(cl);
                    } else {
                        // insert
                        srvcl.create(cl, this.welcomeUI.getUser());
                        if (0 != icl) {
                            majIdClient += ",";
                        } else {
                            icl = 1;
                        }
                        majIdClient += "{\"idAppli\":\"" + cl.getIdAppli() + "\","
                                + "\"idBase\":\"" + cl.getIdBase() + "\"}";                        
                    }
                }
                majIdClient += "]";
                if(icl > 0){
                    this.majIdAppli("clients",majIdClient);
                }
                // verif suppr web
                // recup client nomad
                UtilisateurServices srvuser = new UtilisateurServices();
                List <Client> listClient = srvuser.getClients(this.welcomeUI.getUser());
                // boucler sur client nomad
                for (Client client : listClient){
                    Boolean existClient = false;
                    // a chaque tour verifier l'existence dans json client web
                    for (Object nivone1 : nivone) {
                        JSONObject nivtwo = (JSONObject) nivone1;
                        int idBase = Integer.parseInt(nivtwo.get("id_societe").toString());
                        if(idBase == client.getIdBase()){
                            existClient = true;
                        }
                    }
                    // si n'éxiste pas
                    if(false == existClient){                    
                        // suppr dans nomad
                        System.out.println("on supprime "+ client.getNom());
                        srvcl.delete(client);
                    } else {
                        System.out.println("existe "+ client.getNom());
                    }
                }
                
            }
            // majContacts
            if (jsonObject.containsKey("majContacts")) {
                JSONArray nivone = (JSONArray) jsonObject.get("majContacts");
                ClientServices srvcl = new ClientServices();
                ContactServices srvct = new ContactServices();
                String majIdContact = "[";
                int ict = 0;
                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
//                    Client cl = srvcl.get(Integer.parseInt(nivtwo.get("id_client").toString()));       
                    Client cl = srvcl.getByIdbase(Integer.parseInt(nivtwo.get("id_societe").toString()));       
                    Contact ct = new Contact(Integer.parseInt(nivtwo.get("id_contact").toString()),
                            Integer.parseInt(nivtwo.get("idAppli").toString()),
                            nivtwo.get("nom_contact").toString(),
                            nivtwo.get("prenom_contact").toString(),
                            nivtwo.get("mail_contact").toString(),
                            nivtwo.get("tel_contact").toString(),
                            Boolean.parseBoolean(nivtwo.get("defaut").toString()));
                    if (ct.getIdAppli() > 0) {
                        // update
                        srvct.update(ct);
                    } else {
                        // insert
                        srvct.create(ct, cl);
                        if (0 != ict) {
                            majIdContact += ",";
                        } else {
                            ict = 1;
                        }
                        majIdContact += "{\"idAppli\":\"" + ct.getIdAppli() + "\","
                                + "\"idBase\":\"" + ct.getIdBase() + "\"}";                        
                    }
                }
                majIdContact += "]";
                if(ict > 0){
                    this.majIdAppli("contacts",majIdContact);
                }
            // verif suppr web
                // recup contact nomad
                UtilisateurServices srvuser = new UtilisateurServices();
                List <Client> listClient = srvuser.getClients(this.welcomeUI.getUser());
                
                for (Client client : listClient){
                    List <Contact> listContact = srvcl.getContacts(client);
                    // boucler sur contact nomad
                    for(Contact contact : listContact){
                    Boolean existContact = false;
                        // a chaque tour verifier l'existence dans json contact web
                        for (Object nivone1 : nivone) {
                            JSONObject nivtwo = (JSONObject) nivone1;
                            int idBase = Integer.parseInt(nivtwo.get("id_contact").toString());
                            if(idBase == contact.getIdBase()){
                                existContact = true;
                            }
                        }
                        // si n'éxiste pas
                        if(false == existContact){                    
                            // suppr dans nomad
                            System.out.println("on supprime "+ contact.getMail());
                            srvct.delete(contact);
                        } else {
                            System.out.println("existe "+ contact.getMail());
                        }
                    }
                }
            }
            
            // majAdresses
            if (jsonObject.containsKey("majAdresses")) {
                JSONArray nivone = (JSONArray) jsonObject.get("majAdresses");
                ClientServices srvcl = new ClientServices();
                AdresseServices srvad = new AdresseServices();
                String majIdAdresse = "[";
                int iad = 0;
                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
//                    Client cl = srvcl.get(Integer.parseInt(nivtwo.get("id_client").toString()));
                    Client cl = srvcl.getByIdbase(Integer.parseInt(nivtwo.get("id_societe").toString())); 
                    Adresse ad = new Adresse(Integer.parseInt(nivtwo.get("id_adresse").toString()),
                            Integer.parseInt(nivtwo.get("idAppli").toString()),
                            nivtwo.get("num_voie_adresse").toString(),
                            nivtwo.get("nom_voie_adresse").toString(),
                            nivtwo.get("complement_adresse").toString(),
                            nivtwo.get("cp_adresse").toString(),
                            nivtwo.get("ville_adresse").toString(),
                            nivtwo.get("pays_adresse").toString(),
                            nivtwo.get("mail_adresse").toString(),
                            nivtwo.get("tel_adresse").toString(),
                            Boolean.parseBoolean(nivtwo.get("defaut").toString()));
                    if (ad.getIdAppli() > 0) {
                        // update
                        srvad.update(ad);
                    } else {
                        // insert
                        srvad.create(ad, cl);
                        if (0 != iad) {
                            majIdAdresse += ",";
                        } else {
                            iad = 1;
                        }
                        majIdAdresse += "{\"idAppli\":\"" + ad.getIdAppli() + "\","
                                + "\"idBase\":\"" + ad.getIdBase() + "\"}";                        
                    }
                }
                majIdAdresse += "]";
                if(iad > 0){
                    this.majIdAppli("adresses",majIdAdresse);
                }
            // verif suppr web
                // recup adresse nomad
                UtilisateurServices srvuser = new UtilisateurServices();
                List <Client> listClient = srvuser.getClients(this.welcomeUI.getUser());
                
                for (Client client : listClient){
                    List <Adresse> listAdresse = srvcl.getAdresses(client);
                    // boucler sur adresse nomad
                    for(Adresse adresse : listAdresse){
                    Boolean existAdresse = false;
                        // a chaque tour verifier l'existence dans json adresse web
                        for (Object nivone1 : nivone) {
                            JSONObject nivtwo = (JSONObject) nivone1;
                            int idBase = Integer.parseInt(nivtwo.get("id_adresse").toString());
                            if(idBase == adresse.getIdBase()){
                                existAdresse = true;
                            }
                        }
                        // si n'éxiste pas
                        if(false == existAdresse){                    
                            // suppr dans nomad
                            System.out.println("on supprime "+ adresse.getMail());
                            srvad.delete(adresse);
                        } else {
                            System.out.println("existe "+ adresse.getMail());
                        }
                    }
                }
            }
            
            // majArticles [{"id_article":"85","reference_produit":"CR00X1",
            // "libelle_article":"Comodo X1","id_appli":"26"}]
            if (jsonObject.containsKey("majArticles")) {
                JSONArray nivone = (JSONArray) jsonObject.get("majArticles");
                ClientServices srvcl = new ClientServices();
                ArticleServices srvart = new ArticleServices();
                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
                    Client cl = srvcl.get(Integer.parseInt(nivtwo.get("id_appli").toString()));
                    Article art = new Article();
                    art.setIdBase(Integer.parseInt(nivtwo.get("id_article").toString()));
                    art.setLibelle(nivtwo.get("libelle_article").toString());
                    art.setReference(nivtwo.get("reference_produit").toString());
                    
                   Article artExist = srvart.existByIdbase(art.getIdBase());
                    if (artExist.getIdAppli() > 0) {
                        art.setIdAppli(artExist.getIdAppli());
                        srvart.update(art);
                    } else {
                        srvart.create(art, cl);
                    }
                }
            }
            // majCommandes [{"id_commande":"37","etat_commande":"en cours","id_appli":"1"}]
            if (jsonObject.containsKey("majCommandes")) {
                System.out.println(jsonObject.get("majCommandes"));
                JSONArray nivone = (JSONArray) jsonObject.get("majCommandes");
                CommandeServices srvcom = new CommandeServices();
                for (Object nivone1 : nivone) {
                    JSONObject nivtwo = (JSONObject) nivone1;
                    
                    Commande com = srvcom.get(Integer.parseInt(nivtwo.get("id_appli").toString()));

                    com.setEtatCommande(EtatCommande.getByLibWeb(nivtwo.get("etat_commande").toString()));
                    if (com.getIdAppli() > 0) {
                        srvcom.update(com);
                    }
                 
                }
            }
           // envoie des idAppli créés
            

        } catch (ParseException ex) {
            Logger.getLogger(SynchroAction.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    
    private void majIdAppli(String name, String value){
        try {
                String url = "http://127.0.0.1/NewFilRouge/receive/majidappli";
                HttpClient client = HttpClientBuilder.create().build();
                HttpPost post = new HttpPost(url);
                post.setHeader("User-Agent", USER_AGENT);
                List<NameValuePair> urlParameters = new ArrayList<>();
                
                urlParameters.add(new BasicNameValuePair(name, value));
                
                post.setEntity(new UrlEncodedFormEntity(urlParameters));
//                System.out.println(post);
                HttpResponse response = client.execute(post);
                System.out.println("Response Code : "
                        + response.getStatusLine().getStatusCode());
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(SynchroAction.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(SynchroAction.class.getName()).log(Level.SEVERE, null, ex);
            }
    }
}
